var http=require('http');
var fs=require('fs');

var hostname='127.0.0.1';
var port=3000;

// 创建服务器
 var server=http.createServer(function(req,res){
 	// 跳过chrome的收藏夹图标的请求
 	if (req.url=='/favicon.ico')return;

 	// 获取用户的ip
 	var ip=getIp(req);

 	// 获得随机数 1-9
 	var num=Math.ceil(Math.random()*100000%9);


 	// 读取图片输出
 	fs.readFile('./imgs/'+ num+'.jpg',function(err,data){
 		if (err) throw err;
 		res.writeHead(200,{'content-type':'image/jpg'});
 		res.end(data);
 	});

 });

 // 运行服务器
  server.listen(port,hostname);

// 获取url请求客户端ip
var getIp = function(req) {
    var ip = req.headers['x-forwarded-for'] ||
        req.ip ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress || '';
    if(ip.split(',').length>0){
        ip = ip.split(',')[0]
    }
    return ip;
};
